<?php
namespace control;
/*
*采购询价类
*/
class purchaseInquiryClass extends adIndexClass
{
    private const page = 'purchaseInquiry';
    private const table = 'purchase_inquiry';
    private const tableMx = 'purchase_inquiry_detail';
    private const title = '采购询价';
    public const  scheduleState = ['','是','否'];

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'orderNo'          => [
                'name'  => '单据编号',
                'width' => 150,
                'sort' => 1,
            ],
            'recordDate'          => [
                'name'  => '单据日期',
                'width' => 150,
                'sort' => 1,
            ],
            'purchaseNo' => [
                'name'  => "关联申请单",
                'width' => 200,
            ],
            'text'          => [
                'name'  => '备注',
                'width' => 150,
                'sort' => 1,
            ],
            'state'          => [
                'name'  => '状态',
                'width' => 150,
            ]
        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "采购单据编号"   => text(array("name" => "purchaseNo")),
                ],
                [
                    "单据日期" => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "purchaseNo" => $this->post('purchaseNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            'coid' => self::$coid
        );
        $and = '';
        if ($this->post('recordDate')) {
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] != '草稿' || !$isEdit) {
                unset($dominate['edit']);
            }
            if ($array['isClose'] == 1) {
                $array['state'] = '已完成';
            }
            $closeSign = $array['isClose'] ? "<span class='no-choose'></span>" : '';//关闭单据颜色显示标志
            $liButton[] = $this->dominate($dominate) . $closeSign;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . machiningOrderClass::closeJs() . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 合并物料
     */
    public static function mergeMaterial($listId): array
    {
        $result = [];
        if (empty($listId)) {
            return $result;
        } else {
            $listArr = explode(',', $listId);
            foreach ($listArr as $id) {
                $machining_demands = query('machining_demands', "id = '$id'");
                $material = query('material', "id = '$machining_demands[materialId]'");
                $supplyControl = explode(',', $material['supplyControl']);
                if (in_array('允许采购', (array)$supplyControl)) {
                    if (!array_key_exists($machining_demands['materialId'], $result)) {
                        $result[$machining_demands['materialId']] = [
                            'num' => machiningOrderClass::material_num_change($machining_demands['materialId'], $machining_demands['unit'], $material['unit'], $machining_demands['num']),
                            'unit' => $material['unit'],
                            'materialId' => $machining_demands['materialId'],
                        ];
                    } else {
                        $result[$machining_demands['materialId']]['num'] = $result[$machining_demands['materialId']]['num'] + machiningOrderClass::material_num_change($machining_demands['materialId'], $machining_demands['unit'], $result[$machining_demands['materialId']]['unit'], $machining_demands['num']);
                    }
                }
            }
        }
        return $result;
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name" => "保存为草稿",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[] = ['', '物料编码', '物料名称', '规格型号', '单位',  '图片', '询价明细', '选择供应商','价格', '备注'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' and supplierId = ''",'field' => "*"));
        foreach ($result['array'] as $k=>$array) {
            $detail = query(self::tableMx,"orderId = '$info[id]' and materialId = '$array[materialId]' and is_select = 1");
            $price = $detail['price'] ?: 0;
            $supplierName = $detail['supplierName'] ?: '';
            $material = query('material', " id = '$array[materialId]'");
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
                $material['code'],
                $material['name'],
                $material['model'],
                select(array('name' => 'unitDetail[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $array['unit'])),
                '',
                "<span class=\"smallButton\" onclick=\"layer('{$this->get('cla')}','addSupplier',{id:'".$array['id']."'})\">查看</span>",
                "<span class='supplierName' id='".$array['id']."'>{$supplierName}</span>",
                "<span class='price'>{$price}</span>",
                text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
            ];
        }
        $list = $this->listTable(array('tr' => $tr, 'end' => true,));

//        $chooseBtn = <<<eof
//<span class="smallButton" onclick="layer('{$this->get('cla')}','addMx','{id:{$id}}')">获取明细</span>
//eof;
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    "关联申请单：" =>
                        "<div id='contract' class='full'>$info[purchaseNo]</div>",
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '订单明细',
            'button' => '',
            'html' => $list,
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '采购单', self::page, self::page . 'EditForm')
        ]);

        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $saleOrderObj = new saleOrderClass();
        $data['html'] .= <<<efo
<script>


function addRow(id){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addSupplierEdit',$("form[name='mxForm']").serialize(),function(res) {
            if(res.warn == 2){
                $("#"+res.id).html(res.supplierName);
                $("#"+res.id).parent('td').next().children().html(res.price)
                resetNumber($("#materialTable"));
                $('#purchaseInquiryAddSupplier').remove();//
            }else {
                 returnProcess(res)
            }
        },'json');
}


function suppliereditEdit(){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=suppliereditEdit',$("form[name='purchaseInquirySuppliereditForm']").serialize(),function(res) {
              $("#addSupplierTable tbody").html(res.html);  
              resetNumber($("#addSupplierTable tbody"));
        },'json');
}

function supplierDel(data) {
          $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=supplierDel',data,function(res) {
            
        },'json');
}

</script>
efo. $saleOrderObj->editJs();
        //返回
        return $this->tab($data);
    }

    /**
     * 已在采购单中的数量
     * @param $purchaseOrderId
     * @param $sourceId
     * @param $toUnit
     * @return float
     */
    private function purchaseNum($purchaseOrderId, $sourceId, $toUnit): float
    {
        $refundNum = 0;
        $all = find(array('table' => 'purchase_order_detail', "where" => "sourceId = '$sourceId' and id !='$purchaseOrderId' and coid = '" . self::$coid . "'"));
        foreach ($all['array'] as $array) {
            $refundNum += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $toUnit, $array['num']);
        }
        return self::formattingFigure($refundNum, 'numPrecision');
    }

    public function editEdit()
    { //附件
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $where = " id = '$id' ";
        $info = query(self::table, $where);
//        var_dump($info);die;
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此采购询价单已确认，不能修改';
        } else {
            $json['warn'] = '';
            if (is_array($fileIdArr)) {
                $warn = update(array(
                    'table' => 'file',
                    'field' => ['targetId' => $id],
                    'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                ));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 查看询价明细
     * @return bool|string
     */
    public function addSupplier(): bool|string
    {
        $html = hidden(array('name' => 'id', 'value' => $this->post('id')));
        $html .= "<input onclick=\"layer('purchaseInquiry','supplieredit',{detail_id:'".$this->post('id')."'})\" type='button' class='searchSub m-l-5' value='新增'>";
        $button = "<input onclick=\"addRow();\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html,isSearch:false);//
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 供应商选择
     * @return false|string
     */
    public function supplieredit()
    {
        $id   = $this->post('id');
        $detail_id   = $this->post('detail_id');
        $layerId = $this->get('cla') . ucwords($this->get('fun'));
        $info = query(self::tableMx, " id = '" . $id . "' ");
        $detail = query(self::tableMx, " id = '" . $detail_id . "' ");
        $supplier =  find([
            "table" => self::tableMx,
            "field" => "supplierId",
            "where" => "materialId = '$detail[materialId]' and orderId='$detail[orderId]'  and supplierId != ''",
        ]);
        $supplierIdArr = array_column($supplier['array'],'supplierId');
        $key = array_search($info['supplierId'],$supplierIdArr);
        if($key !== false){
            unset($supplierIdArr[$key]);
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "供应商：" => selectMultiple(["name" => "supplierId", 'value' => $info['supplierId'], 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' and id not in ('".implode("','",$supplierIdArr)."')", 'sqlField' => 'name', 'title' => '供应商名称']),
                    must . "单价（元）：" => text(["name" => "price", 'class' => 'text', "value" => $info['price']]).hidden(array('name' => 'detail_id', 'value' => $this->post('detail_id'))),
                ],
            ],
        ]);
        $button = "<input onclick=\"suppliereditEdit();$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        //返回
        return $this->layer(array("title" => "供应商选择", "height" => 250, "html" => $html,"button" => $button));
    }

    /**
     * 确定供应商选择
     * @return false|string
     */
    public function suppliereditEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'supplierId'       => $this->post('supplierId'),
            'price'       => $this->post('price'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'supplierId' => '供应商',
            'price' => '单价',
        ];
        $rules      = [
            'supplierId' => 'required',
            'price' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = '你还没有编辑权限';
        } else {
            $where = " id = '$id' ";
            $info  = query(self::tableMx, $where);
            $detail  = query(self::tableMx, "id = '".$this->post('detail_id')."'");
            $supplier  = query('supplier', "id = '".$field['supplierId']."'");
            $min_price = query( "purchase_order_detail as a join purchase_order as b on a.orderId = b.id "," b.supplierId='$field[supplierId]' and a.materialId='$detail[materialId]' group by b.id",'min(a.price) as price');
            if (!$info['id']) {
                $field        = array_merge($field, [
                    'id'      => $id,
                    'coid' => $detail['coid'],
                    'orderId' => $detail['orderId'],
                    'materialId' => $detail['materialId'],
                    'supplierName' => $supplier['name'],
                    'unit' => $detail['unit'],
                    'num' => $detail['num'],
                    'money' => self::lostZero($detail['num'] * $field['price']),
                    'history_min' => $min_price['price'] ?? 0,
                    'is_select'    => 0,
                    'rate'    => 0,
                    'text'    => '',
                    'time'    => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::tableMx, "field" => $field]);
            } else {
                $field        = array_merge($field, [
                    'supplierName' => $supplier['name'],
                    'money' => self::lostZero((float)$detail['num'] * (float)$field['price']),
                    'history_min' => $min_price['price'] ?? 0,
                ]);
                $json['warn'] = static::update([
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = $this->control['name']. "修改了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn']     = 2;

                $like = [];
                $equal = [
                    'materialId' => $info['materialId'],
                    'orderId' => $info['orderId'],
                ];
                $where = search(["like" => $like, "=" => $equal]). " and supplierId != ''";
                $page = $this->page([
                    "table" => self::tableMx,
                    "field" => "*",
                    "where" => $where,
                    'pageNum' => 50,
                    "order" => "time desc",
                ]);
                foreach ($page['array'] as $key=>$array) {
                    if($array['is_select'] == 1) {
                        $checkBox = "<input name='mxId' value='$array[id]'  type='radio' checked='checked'>";
                    }else{
                        $checkBox = "<input name='mxId' value='$array[id]'  type='radio'>";
                    }
                    $tr[] = array(
                        $checkBox. hidden(array('name' => 'count_id[]', 'value' => $array['id'])),
                        $key+1,
                        $array['supplierName'],
                        self::lostZero($array['price'],'pricePrecision'),
                        $array['history_min'],
                        componentClass::tablePperation(del:"delTableRow(this);supplierDel({id:\"".$array['id']."\"})",edit:"layer(\"purchaseInquiry\",\"supplieredit\",{detail_id:\"".$info['id']."\",id:\"".$array['id']."\"})"),
                    );

                }
                $json['html'] = $this->tableMany(array("tr" => $tr,"thead" => false));
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 询价明细
     * @return bool|string
     */
    public function addSupplierSearch(): bool|string
    {
        $info  = query(self::tableMx, "id = '".$this->post('id')."'");
        $like = [];
        $equal = [
            'materialId' => $info['materialId'],
            'orderId' => $info['orderId'],
        ];
        $where = search(["like" => $like, "=" => $equal]). " and supplierId != ''";
        $page = $this->page([
            "table" => self::tableMx,
            "field" => "*",
            "where" => $where,
            'pageNum' => 50,
            "order" => "time desc",
        ]);
        //获取表头
        $tr[] = ['', '序号', '供应商名称', '价格', '历史最低价格', '操作'];
        //获取记录
        foreach ($page['array'] as $key=>$array) {
            if($array['is_select'] == 1) {
                $checkBox = "<input name='mxId' value='$array[id]'  type='radio' checked='checked'>";
            }else{
                $checkBox = "<input name='mxId' value='$array[id]'  type='radio'>";
            }
            $tr[] = array(
                $checkBox. hidden(array('name' => 'count_id[]', 'value' => $array['id'])),
                $key+1,
                $array['supplierName'],
                self::lostZero($array['price'],'pricePrecision'),
                $array['history_min'],
                componentClass::tablePperation(del:"delTableRow(this);supplierDel({id:\"".$array['id']."\"})",edit:"layer(\"purchaseInquiry\",\"supplieredit\",{detail_id:\"".$info['id']."\",id:\"".$array['id']."\"})"),
            );

        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm' id='addSupplierTable'>". hidden(array('name' => 'id', 'value' => $info['id'])) .
            $this->tableMany(array("tr" => $tr, "end" => true)) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 删除供应商报价
     *
     */
    public function supplierDel()
    {
        $id = $this->post('id');
        if(!$id){
            $json['warn'] = '删除失败';
        }else{
            delete(array("table" => self::tableMx, "where" => " id = '$id' "));
            $json['warn'] = '删除成功';
        }
        return json_encode($json, 320);
    }
    /**
     * 关联询价明细
     */
    public function addSupplierEdit()
    {
        $mxId = $this->post('mxId');
        $countIdArr = $this->post('count_id');
        $id = $this->post('id');
        $info  = query(self::tableMx, "id = '".$mxId."'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxId)){
            $json['warn'] = '请选择供应商价格';
        } elseif (count($countIdArr) < 3){
            $json['warn'] = '物料供应商少于三个';
        }else {
            update(array('table' => self::tableMx, 'field' => ['is_select' => 0], 'where' => "materialId='$info[materialId]' and orderId='$info[orderId]'"));
            update(array('table' => self::tableMx, 'field' => ['is_select' => 1], 'where' => "id = '$mxId'"));
            $json['warn'] = 2;
            $json['id'] = $id;
            $json['price'] = $info['price'].'';
            $json['supplierName'] = $info['supplierName'];
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "复核",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => self::title,
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }

            }
            //按钮
//            $button[] = [
//                "name" => "打印",
//                "type" => "点击事件",
//                "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
//            ];

            if ($this->power(self::page, "confirm") && $info['state'] != '草稿' && !$info['isClose']) {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }

            $tr[] = ['物料编码', '物料名称', '规格型号', '单位',  '图片', '询价明细', '选择供应商','价格','数量', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' and supplierId = ''",'field' => "*"));
            $totalArr = ['num'=>0];
            foreach ($result['array'] as $array) {
                $detail = query(self::tableMx,"orderId = '$info[id]' and materialId = '$array[materialId]' and is_select = 1");
                $price = $detail['price'] ?: 0;
                $supplierName = $detail['supplierName'] ?: '';
                $material = query('material', " id = '$array[materialId]'");
                $tr[] = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    '',
                    "",
                    $supplierName,
                    $price,
                    self::lostZero($array['num'],'numPrecision'),
                    $array['text'],
                ];
                $totalArr['num'] += $array['num'];
            }
            $total_tr = [
                8=>$totalArr['num']?self::lostZero($totalArr['num'],'numPrecision'): 0,
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                array(
                    array(
                        "单据日期" => self::null($info['recordDate']),
                        "关联申请单" => $info['purchaseNo'],
                        "备注" => pre($info['text']),
                    ),
                    array(
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']. self::operateRecord($info['id']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '订单明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr,'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], self::title),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 操作记录
     */
    public static function operateRecord($id): string
    {
        $result = find(['table' => 'auditing_follow', 'where' => "typeId = '$id' order by time desc"]);
        $li     = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li>{$array['text']}&emsp;{$array['time']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>暂无记录</li>";
        }
        return "&emsp;<span class='del-row-button' id='record'>操作记录<div class='stateBlock operate-content'><ul>$li</ul></div></span>";
    }
    /**
     * 确认
     */
    public function batchSureEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有操作的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id'");
                $field = [
                    'state' => '已确认',
                    'checkId' => self::$stid,
                    'confirmTime' => $this->time
                ];
                if (empty($info['id'])) {
                    $json['warn'] = '未找到此采购询价单';
                    goto resp;
                } elseif (!in_array($info['state'],['草稿','待确认'])) {
                    $json['warn'] = '此采购询价单不是草稿、待确认状态，不能确认';
                    goto resp;
                }
                $this->startTrans();
                $json['warn'] = update(array(
                    "table" => self::table,
                    "field" => $field,
                    "where" => "id = '$info[id]'",
                ));
                resp:
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    // 根据采购数量关闭采购申请
                    $this->commitTrans();
                    if($info['state'] == '草稿') {
                        $operate = "提交，确认";
                    }else{
                        $operate = "确认";
                    }
                    auditClass::operateRecord($id, self::title, $operate);
                    //添加日志
                    $warn = $operate."成功";
                    $x++;
                } else {
                    $this->rollback();
                    $warn = $json['warn'];
                }

                $text .= self::title . "单据编号【" . $info['orderNo'] . "】，ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "提交，确认了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "提交，确认了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此采购单不是待确认状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购询价单';
        } elseif ($info['state'] == '草稿') {
            $json['warn'] = '此采购询价单草稿状态，无需撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 根据采购数量关闭采购申请
                $this->updatePurchaseApply($info);
                self::insertOperateLog($info['id'],self::title,"撤回");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $result = find(array('table' => self::tableMx, 'field' => 'id,materialId,num,unit,price', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) < 4){
            return "请完善采购询价明细";
        }

        return true;
    }
    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购询价单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此采购询价单不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此采购单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此采购单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此采购单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'close':
                $act = 'close';
                $msg = '业务关闭';
                $title = '是否确认批量关闭采购订单？';
                $function = 'closeEdit';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                $word = true;
                break;
            case 'batchSure':
                $act = 'edit';
                $msg = '提交确认';
                $title = '是否确认批量提交确认采购订单？';
                $function = 'batchSureEdit';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 批量关闭采购订单
     *
     * @return bool|string
     */
    public function closeEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有操作的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ", "isClose");
                if ($info['isClose'] == 1) {
                    $warn = "操作失败：已关闭，请勿重复操作";
                } else {
                    update(array('table' => self::table, 'field' => ['isClose' => 1], 'where' => " id = '$id' "));
                    self::insertOperateLog($id,self::title,"关闭");
                    //返回
                    $warn = "关闭成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "关闭了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "关闭了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    fileClass::deleteFile($id);
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit('参数错误');
        } else {
            $listId = base64_decode($lists, true);
            $array = explode(',', $listId);
            $data = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(self::page, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id = $param ?: $this->get('id');
        $info = query(self::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['checkId'] = '';
        $info['supplierName'] = query('supplier', "id = '$info[supplierId]'")['name'];
        $info['qr'] = "source=" . self::table . "&id=" . $info['id'];
        $info['tags'] = orderTagClass::getTagName($info['id']);
        $detail = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items = [];
        $x = 1;
        $totalNum = 0;
        $totalMoney = 0;
        foreach ($detail as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $items[] = [
                'no' => $x,
                'materialCode' => $material['code'],
                'materialName' => $material['name'],
                'price' => self::lostZero($array['price'], 'pricePrecision'),
                'rate' => ($array['rate'] * 100) . '%',
                'taxMoney' => self::lostZero($array['taxMoney']),
                'moneyWithOutTax' => self::formattingFigure($array['money'] - $array['taxMoney']),
                'money' => self::lostZero($array['money']),
                'model' => $material['model'],
                'unit' => $array['unit'],
                'num' => self::lostZero($array['num'], 'numPrecision'),
                'text' => $array['text'],
            ];
            $x++;
            $totalNum += $array['num'];
            $totalMoney += $array['money'];
        }
        $append = [
            'no' => '合计',
            'num' => $totalNum,
            'money' => $totalMoney
        ];
        $items[] = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(self::page, $info);
        } else {
            return $info;
        }
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'采购合同编号',
                    'aliasName'=>'采购合同编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'采购合同名称',
                    'aliasName'=>'采购合同名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'结算方式',
                    'aliasName'=>'结算方式',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'结算周期',
                    'aliasName'=>'结算周期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'交货日期',
                    'aliasName'=>'交货日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收货人',
                    'aliasName'=>'收货人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收货电话',
                    'aliasName'=>'收货电话',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收货地址',
                    'aliasName'=>'收货地址',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据备注',
                    'aliasName'=>'单据备注',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'是否含税',
                    'aliasName'=>'是否含税(是/否，默认否)',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'税率',
                    'aliasName'=>'税率%',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }
}